package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.actuate.metrics.MetricsEndpoint;
import org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: demo
 * @description:
 * @author: zt22328 赵儒定
 * @create: 2022-06-28 11:11
 **/
@RestController
public class HealthController {

//    @Resource
//    MetricsEndpoint metricsEndpoint;

    volatile boolean flag = false;

    @GetMapping("/actuator/metrics2")
    public Object metrics2(String flag){
        Map<String,Double> map = new HashMap<>();
//        metricsEndpoint.listNames().getNames().forEach(e->{
//            Double value = metricsEndpoint.metric(e, null).getMeasurements().get(0).getValue();
//            map.put(e,value);
//        });
        if(flag!=null){
            this.flag = true;
        }
//        whiles();
        return map;
    }

    private void whiles() {
        while (flag){

        }
    }

    private List<String> HEALTH_NAMES = Arrays.asList("system.cpu.usage","process.cpu.usage");//,"jvm.memory.max","jvm.memory.used"

    @GetMapping("/status")
    public Object health2(HttpServletResponse response){

        response.addIntHeader("weight",getWeight());
        return "OK";
    }

    private int getWeight() {
        AtomicReference<Double> cpu = new AtomicReference<>(0D);
//        HEALTH_NAMES.forEach(e->{
//            Double value = metricsEndpoint.metric(e, null).getMeasurements().get(0).getValue();
//            cpu.updateAndGet(v -> v + value);
//        });
        int freeCpu = (int) ((1-cpu.get())*100) - 20;
        if(freeCpu<=0){
            return 0;
        }
        return freeCpu;
    }
}
